package hanhns.test.provider_database;


import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.util.Log;

import java.util.HashMap;

public class BNoteProvider extends ContentProvider {
	
    private static final String TAG = "BNoteProvider";
    
    public static final String AUTHORITY = "com.bkav.provider.bNote";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/notes");
    
    //Ten database, bang, cac cot trng bang.
    public static final String DATABASE_NAME = "bNote_provider";
    public static final String NOTE_TABLE_NAME = "notes";
    public static final String _ID_COLUMN = "_id";
    public static final String NOTE_TITLE_COLUMN = "title";
    public static final String NOTE_CONTENT_COLUMN = "content";
    public static final String NOTE_CHECK = "checked";
    private static final int DATABASE_VERSION = 1;
    
    private static final int NOTES = 1;
    private static final int NOTE_ID = 2;
//    private static final int INSERT = 3;
    
    public static UriMatcher sUriMathCher;
    private static HashMap<String, String> sNoteColumnMap;
    
    static {
        sUriMathCher  = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMathCher.addURI(AUTHORITY, "notes", NOTES);
        sUriMathCher.addURI(AUTHORITY, "notes/#", NOTE_ID);
//        sUriMathCher.addURI(AUTHORITY, "notes", INSERT);
        
        sNoteColumnMap  = new HashMap<String, String>();
        sNoteColumnMap.put(_ID_COLUMN, _ID_COLUMN);
        sNoteColumnMap.put(NOTE_TITLE_COLUMN, NOTE_TITLE_COLUMN);
        sNoteColumnMap.put(NOTE_CONTENT_COLUMN, NOTE_CONTENT_COLUMN);
    }
        
    /**
    * The MIME type of {@link #CONTENT_URI} providing a directory of notes
    */
   public static final String CONTENT_TYPE = "vnd.android.cursor.dir/other.note.muti";

   /**
    * The MIME type of a {@link #CONTENT_URI} sub-directory of a single note.
    */
   public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.bkav.note";
   
   
   /**
    * This class helps open, create, and upgrade the database file.
    */
    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + NOTE_TABLE_NAME + " ("
                   + _ID_COLUMN + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                   + NOTE_TITLE_COLUMN + " TEXT NOT NULL,"
                   + NOTE_CONTENT_COLUMN + " TEXT" //+ ","
//                   + NOTE_CHECK + " BOOL DEFAULT true"
                   + ");");
       }

       @Override
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
           Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                   + newVersion + ", which will destroy all old data");
           db.execSQL("DROP TABLE IF EXISTS notes");
           onCreate(db);
       }
   }

    
    
    private DatabaseHelper mOpenHelper;
    private SQLiteDatabase mData;
    
    @Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
    	Log.e(TAG, "oncreatt");
		mOpenHelper = new DatabaseHelper(this.getContext());
		mData = mOpenHelper.getWritableDatabase();
		return (mData != null) ? true : false;
	}
    
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
//		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMathCher.match(uri)) {
        case NOTES:     // xoa tat ca note.
            count = mData.delete(NOTE_TABLE_NAME, selection, selectionArgs);
            break;

        case NOTE_ID:	// Xoa mot note
            String userId = uri.getPathSegments().get(1);
            count = mData.delete(NOTE_TABLE_NAME, _ID_COLUMN + "=" + userId, selectionArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        
        Log.e("provider_method_delete", count + "");
        return count;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		switch (sUriMathCher.match(uri)){
			case NOTES:
//			case INSERT:
				return CONTENT_TYPE;
			case NOTE_ID:
				return CONTENT_ITEM_TYPE;
			default:
				throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		// TODO Auto-generated method stub
		// Validate the requested uri
        if (sUriMathCher.match(uri) != NOTES) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        
	    ContentValues values;
	    if (initialValues != null) {
	        values = new ContentValues(initialValues);
	    } else {
	        values = new ContentValues();
	    }
	    // Make sure that the fields are all set
	    if (values.containsKey(NOTE_TITLE_COLUMN) == false) {
            values.put(NOTE_TITLE_COLUMN, "");
        }
	    if (values.containsKey(NOTE_CONTENT_COLUMN) == false) {
            values.put(NOTE_CONTENT_COLUMN, "");
        }
	    mData = mOpenHelper.getWritableDatabase();
	    long rowId = mData.insert(NOTE_TABLE_NAME,  null, values);
	    if (rowId > 0) {
	       Uri noteUri = ContentUris.withAppendedId(CONTENT_URI, rowId);
	       getContext().getContentResolver().notifyChange(noteUri, null);
	       return noteUri;
	    }
	    throw new SQLException("Failed to insert row into " + uri);
	}

	
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(NOTE_TABLE_NAME);
        
        switch (sUriMathCher.match(uri)) {
        case NOTES:
        	Log.e("hanhns", "provider query");
            qb.setProjectionMap(sNoteColumnMap);
            break;

        case NOTE_ID:
        	Log.e("hanhns", "provider select id");
            qb.setProjectionMap(sNoteColumnMap);
            qb.appendWhere(_ID_COLUMN + "=" + uri.getPathSegments().get(1));
            break;
//        case INSERT:
//        	Log.e("hanhns", "insert");
//            qb.setProjectionMap(sNoteColumnMap);
//            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        // Get the database and run the query
//        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Log.e("hanhns", "befor query");
        Cursor c = qb.query(mData, projection, selection, selectionArgs, null, null, sortOrder);
        Log.e("hanhns", "after query");

        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
//		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMathCher.match(uri)) {
        case NOTES://update multi row.
            count = mData.update(NOTE_TABLE_NAME, values, selection, selectionArgs);
            break;

        case NOTE_ID:
            String userID = uri.getPathSegments().get(1);
            count = mData.update(NOTE_TABLE_NAME, values, _ID_COLUMN + "=" + userID, selectionArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}
	
//	public int totalChecked(Uri uri){
//		int total = 0;
//		String query = "select count(*) from " + BNoteProvider.NOTE_TABLE_NAME + " where " + BNoteProvider.NOTE_CHECK + " = true";
//		Cursor cursor = mData.rawQuery(query, null);
//		if ( cursor != null && cursor.getCount() > 0){
//			cursor.moveToFirst();
//			total = cursor.getInt(1);
//		}
//		return total;
//	}
}
